<template>
  <div class="table-box">
    <ProTable ref="proTable" :columns="columns" :request-api="getTableList" :data-callback="dataCallback">
      <template #tableHeader>
        <el-button v-auth="'add'" icon="Plus" type="primary" @click="addProjectAnnexFn"> 新增 </el-button>
      </template>
      <template #reportImgModels="scope">
        <el-image
          v-for="url in scope.row.reportImgModels"
          :key="url"
          style="width: 23px; height: 23px; margin-right: 2px"
          :src="urlResource + url.path"
          :zoom-rate="1.2"
          true
          :max-scale="7"
          :min-scale="0.2"
          :preview-src-list="[urlResource + url.path]"
          :initial-index="4"
          :z-index="100000000000000000"
          :preview-teleported="true"
          fit="cover"
        />
      </template>
      <template #gmtCreate="{ row }">
        {{ row.gmtCreate }}
      </template>
      <template #projectName="{ row }">
        {{ row.projectName }}
      </template>
      <template #userName="{ row }">
        {{ row.userName }}
      </template>
      <template #todayContent="{ row }">
        <span class="sle">{{ row.todayContent }}</span>
      </template>
      <template #tomorrowContent="{ row }">
        <span class="sle">{{ row.tomorrowContent }}</span>
      </template>
      <template #todayProblem="{ row }">
        <span class="sle">{{ row.todayProblem }}</span>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" v-auth="'get'" link @click="editFn(scope.row, 1)">查看</el-button>
        <el-button type="primary" v-auth="'update'" link @click="editFn(scope.row)"> 编辑 </el-button>
        <el-button type="primary" v-auth="'delete'" link @click="deleteHandler(scope.row)"> 删除 </el-button>
      </template>
    </ProTable>
    <div v-if="drawerVisible">
      <Dialog
        v-model:drawerVisible="drawerVisible"
        v-model:config="config"
        class-name="dialog-form-report-daily"
        @change="successCallback"
      >
      </Dialog>
    </div>
  </div>
</template>
<script lang="ts" setup name="reportDaily">
import ProTable from "@/components/ProTable/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { reportPage } from "@/api/modules/statistics";
import { ref, onMounted } from "vue";
import { PROJECTIMG } from "@/constants";
import { useHandleData } from "@/hooks/useHandleData";
import Dialog from "@/components/DialogForm/index.vue";
// api
import { addReport, deleteReport, updateReport } from "@/api/modules/project";
import { getProjectListCodeAll } from "@/api/modules/project";
import { getListAllUser } from "@/api/modules/sys";

const urlResource = window?.staticConfig.urlResource;
const proTable = ref<ProTableInstance>();
const getTableList = async (params: any) => {
  // 时间转化
  const startTime = params.timeCustomer[0] || undefined;
  const endTime = params.timeCustomer[1] || undefined;
  const newParams = {
    currentPage: params.pageNum,
    searchKey: params.searchKey ? params.searchKey : "",
    projectId: params.projectId || undefined,
    userId: params.userId || undefined,
    startTime,
    endTime
  };
  return reportPage(newParams);
};
// 变量
let drawerVisible = ref(false);
let config = ref<any>({ width: 60 });
const listAllUser = ref<any>([]);
const projectList = ref<any>([]);

// 表格配置项
const columns: ColumnProps[] = [
  { prop: "userId", label: "用户ID", isShow: false },
  { prop: "projectId", label: "项目ID", isShow: false },
  {
    prop: "projectName",
    label: "订单名称",
    search: { el: "select", label: "订单名称", key: "projectId", props: { filterable: true } },
    enum: async () => await getProjectPageFn(),
    fieldNames: { label: "name", value: "id" }
  },
  {
    prop: "projectCode",
    label: "订单编号"
  },
  {
    prop: "userName",
    label: "用户名",
    search: { el: "select", label: "用户名", key: "userId", props: { filterable: true } },
    enum: async () => await getListAllUserFn(),
    fieldNames: { label: "name", value: "id" }
  },
  { prop: "taskId", label: "项目任务ID", isShow: false },
  {
    prop: "todayContent",
    label: "今日工作内容",
    search: {
      el: "date-picker",
      label: "创建时间",
      key: "timeCustomer",
      props: { type: "daterange", valueFormat: "YYYY-MM-DD HH:mm:ss", clearable: true },
      defaultValue: []
    },
    showOverflowTooltip: false
  },
  { prop: "tomorrowContent", label: "明日工作内容", showOverflowTooltip: false },
  { prop: "todayProblem", label: "今日工作问题", showOverflowTooltip: false },
  { prop: "remark", label: "备注", isShow: false },
  { prop: "reportImgModels", label: "日报图片", className: "img-box" },
  { prop: "gmtCreate", label: "创建时间" },
  { prop: "operation", label: "操作", width: 180 }
];

const dataCallback = (data: any) => {
  // 处理字段文字
  return {
    list: data.records,
    total: Number(data.total),
    pageNum: Number(data.current),
    pageSize: Number(data.size)
  };
};

// 新增日报
const addProjectAnnexFn = () => {
  drawerVisible.value = true;
  drawerVisible.value = true;
  config.value.title = "新增日报";
  config.value.width = 95;
  config.value.form = {
    formData: {
      id: "",
      projectId: "",
      projectName: "",
      projectCode: "",
      // userId: "",
      todayContent: "",
      tomorrowContent: "",
      todayProblem: "",
      remark: "",
      reportImgModels: []
    },
    rules: {
      // userId: [{ required: true, message: "请选择人员" }],
      projectId: [{ required: true, message: "请选择订单" }],
      todayContent: [{ required: true, message: "请填写今日工作内容" }],
      tomorrowContent: [{ required: true, message: "请填写明日工作内容" }],
      todayProblem: [{ required: true, message: "请填写今日工作问题" }],
      reportImgModels: [{ required: true, message: "请上传图片" }]
    }
  };
  config.value.column = [
    // {
    //   type: "group",
    //   title: "",
    //   direction: "",
    //   list: [
    // {
    //   type: "select",
    //   key: "userId",
    //   formItemAttribute: {
    //     label: "提交人员"
    //     // "label-position": "right"
    //   },
    //   attributes: {
    //     placeholder: "请选择提交人员",
    //     options: listAllUser.value,
    //     multiple: false,
    //     filterable: true,
    //     clearable: true
    //   }
    // }
    // {
    //   type: "select",
    //   key: "isClose",
    //   formItemAttribute: {
    //     label: "是否关闭",
    //     "label-position": "right"
    //   },
    //   attributes: {
    //     placeholder: "请选择是否关闭",
    //     options: [
    //       {
    //         label: "是",
    //         value: true
    //       },
    //       {
    //         label: "否",
    //         value: false
    //       }
    //     ],
    //     clearable: true
    //   },
    //   fieldNames: {
    //     label: "label",
    //     value: "value"
    //   }
    // }
    //   ]
    // },
    {
      type: "group",
      title: "现场图片",
      direction: "",
      len: 1,
      layout: "grid",
      list: [
        {
          type: "file",
          key: "reportImgModels",
          formItemAttribute: {
            label: ""
          },
          attributes: {
            "prefix-data": PROJECTIMG,
            multiple: true,
            showFileList: true,
            limit: 30,
            width: "340px",
            height: "340px",
            type: "image",
            listType: "picture-card",
            fileType: ["image/jpeg", "image/png", "image/gif"]
          }
        }
      ]
    },
    {
      type: "group",
      title: "日报记录",
      direction: "",
      len: 1,
      layout: "grid",
      list: [
        {
          type: "select",
          key: "projectId",
          formItemAttribute: {
            label: ""
          },
          attributes: {
            placeholder: "请选择订单",
            options: projectList.value,
            multiple: false,
            filterable: true,
            clearable: true,
            disabled: false,
            changeFn: (val: any, originConfig: any) => {
              const country = projectList.value.find((item: any) => item.id === val);
              originConfig.formData.projectName = country?.name;
              originConfig.formData.projectCode = country?.code;
              console.log("originConfig", country);
            }
          },
          fieldNames: { label: "nameClone", value: "id" }
        },
        {
          type: "input",
          key: "todayContent",
          formItemAttribute: {
            label: "今日工作事项"
          },
          attributes: {
            placeholder: "请填写今日工作事项",
            type: "textarea",
            rows: 4
          }
        },
        {
          type: "input",
          key: "todayProblem",
          formItemAttribute: {
            label: "今日工作问题"
          },
          attributes: {
            placeholder: "请填写今日工作问题",
            type: "textarea",
            rows: 4
          }
        },
        {
          type: "input",
          key: "tomorrowContent",
          formItemAttribute: {
            label: "明日工作事项"
          },
          attributes: {
            placeholder: "请填写明日工作事项",
            type: "textarea",
            rows: 4
          }
        }
      ]
    }
  ];
  config.value.api = addReport;
  config.value.transformData = (data: any) => {
    data.reportImgModels = data.reportImgModels.map((item: any) => {
      return {
        name: item.name,
        originalName: item.originalName,
        path: item.path
      };
    });
    delete data.id;
    return JSON.parse(JSON.stringify(data));
  };
  config.value.message = "添加成功";
};

// 编辑、查看日报
const editFn = (preData: any, type?: any) => {
  config.value.width = 95;
  drawerVisible.value = true;
  config.value.title = type ? "查看日报" : "编辑日报";
  config.value.form = {
    formData: {
      id: preData.id,
      projectId: preData.projectId,
      projectName: preData.projectName,
      projectCode: preData.projectCode,
      // userId: preData.userId,
      todayContent: preData.todayContent,
      tomorrowContent: preData.tomorrowContent,
      todayProblem: preData.todayProblem,
      remark: "",
      reportImgModels:
        preData.reportImgModels &&
        preData.reportImgModels.map(item => {
          item.url = urlResource + item.path;
          return item;
        })
    },
    rules: {
      // userId: [{ required: true, message: "请选择人员" }],
      projectId: [{ required: true, message: "请选择项目" }],
      todayContent: [{ required: true, message: "请填写今日工作内容" }],
      tomorrowContent: [{ required: true, message: "请填写明日工作内容" }],
      todayProblem: [{ required: true, message: "请填写今日工作问题" }],
      reportImgModels: [{ required: true, message: "请上传图片" }]
    },
    attribute: {
      disabled: type === 1
    }
  };
  config.value.column = [
    {
      type: "group",
      title: "现场图片",
      direction: "",
      len: 1,
      layout: "grid",
      list: [
        {
          type: "file",
          key: "reportImgModels",
          formItemAttribute: {
            label: ""
          },
          attributes: {
            "prefix-data": PROJECTIMG,
            multiple: true,
            showFileList: true,
            limit: 30,
            width: "340px",
            height: "340px",
            type: "image",
            listType: "picture-card",
            fileType: ["image/jpeg", "image/png", "image/gif"]
          }
        }
      ]
    },
    {
      type: "group",
      title: "日报记录",
      direction: "",
      len: 1,
      layout: "grid",
      list: [
        {
          type: "select",
          key: "projectId",
          formItemAttribute: {
            label: ""
          },
          attributes: {
            placeholder: "请选择项目",
            options: projectList.value,
            multiple: false,
            filterable: true,
            clearable: true,
            changeFn: (val: any, originConfig: any) => {
              const country = projectList.value.find((item: any) => item.id === val);
              originConfig.formData.projectName = country?.name;
              originConfig.formData.projectCode = country?.code;
            }
          },
          fieldNames: { label: "nameClone", value: "id" }
        },
        {
          type: "input",
          key: "todayContent",
          formItemAttribute: {
            label: "今日工作事项"
          },
          attributes: {
            placeholder: "请填写今日工作事项",
            type: "textarea",
            rows: 4
          }
        },
        {
          type: "input",
          key: "todayProblem",
          formItemAttribute: {
            label: "今日工作问题"
          },
          attributes: {
            placeholder: "请填写今日工作问题",
            type: "textarea",
            rows: 4
          }
        },
        {
          type: "input",
          key: "tomorrowContent",
          formItemAttribute: {
            label: "明日工作事项"
          },
          attributes: {
            placeholder: "请填写明日工作事项",
            type: "textarea",
            rows: 4
          }
        }
      ]
    }
  ];
  config.value.api = updateReport;
  config.value.transformData = (data: any) => {
    data.reportImgModels = data.reportImgModels.map(item => {
      return {
        name: item.name,
        originalName: item.originalFileName,
        path: item.path
      };
    });
    return JSON.parse(JSON.stringify(data));
  };
  config.value.message = "编辑成功";
};

const successCallback = () => {
  proTable.value?.getTableList();
};

// 删除
const deleteHandler = async (params: any) => {
  await useHandleData(deleteReport, { id: params.id }, `删除【日报】`);
  proTable.value?.getTableList();
};
// 获取全部用户
const getListAllUserFn = async () => {
  const { data } = await getListAllUser();
  listAllUser.value = data;
  return Promise.resolve({ data: data });
};
const getProjectPageFn = async () => {
  try {
    const { data } = await getProjectListCodeAll();
    projectList.value =
      (data &&
        data.map((item: any) => {
          item.nameClone = item.code + "-" + item.name;
          return item;
        })) ||
      [];
    return {
      data: data.records || []
    };
  } catch (error) {
    console.log(error);
  }
};
onMounted(async () => {
  await getProjectPageFn();
});
</script>
<style lang="scss" scoped>
@import "./index.scss";
:deep(.el-table) {
  .img-box {
    text-align: left;
  }
}
</style>
<style lang="scss">
.dialog-form-report-daily {
  height: 90vh;
  --el-dialog-margin-top: 0 !important;
  .info-form {
    display: grid;
    grid-template-columns: minmax(0, 1.5fr) minmax(0, 1fr);
    .el-form-item:nth-child(2) {
      .group {
        position: relative;
        .group-wrap > div:first-child {
          position: absolute;
          right: 0;
          top: 0;
          width: 150px !important;
          cursor: pointer;
          .el-form-item {
            background: transparent;
            cursor: pointer;
            padding: 0;
            .el-select__wrapper {
              font-size: 14px;
              cursor: auto;
              background: none;
              border: 0;
              padding: 0;
              box-shadow: none;
              display: flex;
              flex-flow: row-reverse nowrap;
              align-items: center;
              .el-select__suffix {
                display: block;
                .el-icon {
                  color: $primary-color;
                }
              }
              .el-select__selected-item {
                color: $primary-color;
              }
              .el-select__input {
                cursor: pointer;
              }
            }
          }
        }
        .el-form-item:last-child {
          padding: 20px;
          background: #f5f7fa;
        }
      }
    }
  }
}
</style>
